<?php
/**
 * Created by PhpStorm.
 * User: 汪利东
 * Date: 2016/3/24
 * Time: 17:34
 */
namespace Admin\Controller;
class AdminUserController extends BaseController {

    public function index() {
        $data = D('AdminUser')->relation(TRUE)->select();
        $this->data = $data;
        $this->display();
    }

    public function add() {
        $group = M('AdminGroup')->select();
        $this->group = $group;
        $this->display('edit');
    }

    public function edit() {
        $user_id = I('get.user_id');
        $data = M('AdminUser')->where(['user_id' => $user_id])->find();
        $this->data = $data;
        $group_id = M('AdminGroupHasUser')->where(['uid' => $user_id])->getField('group_id');
        $group = M('AdminGroup')->select();
        $this->group_id = $group_id;
        $this->group = $group;
        $this->display();
    }

    public function doEdit() {
        $user_id = I('get.user_id');
        $group_id = I('post.group_id');
        $data = M('AdminUser')->create();
        if (empty($user_id)) {
            //新增
            $r = M('AdminUser')->where(['account' => $data['account']])->find();
            if (!empty($r)) {
                $this->error('此账号已存在，请更换');
            }
            M('AdminUser')->startTrans();
            $r = M('AdminUser')->add($data);
            $res = M('AdminGroupHasUser')->add(['uid' => $r, 'group_id' => $group_id,]);
            if ($r && $res) {
                M('AdminUser')->commit();
                $this->success('新增成功', U('index'));
            } else {
                M('AdminUser')->rollback();
                $this->erroe('新增失败');
            }
        } else {
            //编辑
            M('AdminUser')->startTrans();
            $r = M('AdminUser')->where(['user_id' => $user_id])->save($data);
            $res = M('AdminGroupHasUser')->where(['uid' => $user_id])->save(['group_id' => $group_id]);
            if ($r || $res) {
                M('AdminUser')->commit();
                $this->success('编辑成功');
            } else {
                M('AdminUser')->rollback();
                $this->erroe('失败');
            }
        }
    }
}